/*
 * @Description: 打印相关
 */
import globalMethods from '@/plugins/methods';
import sendCommon from '@/handles/common/send';
import printFragmentObj from './fragment';
import {getWaterMarkBase64} from "@/plugins/directives/modules/watermark";
// import Vue from 'vue';
// 附言
// 意见
// import OpinionArea from '@/layout/widgets/collab-sider-approval-opinions/src/opinion-area/index.vue';
// import OpinionArea from '@/components/opinion-area/index.vue';

/**
 * @description: 组装协同打印模块
 * @param {string} printFrom 打印的类型吧我觉得是。表单正文和我们自己逻辑都要用
 * @return {Array}返回一个正文前打印的内容、正文后打印的内容的数组
 */
export function createPrintFragment(printFrom, beforeContentDefault, afterContentDefault) {
  if (printFragmentObj.isLoading) {
    return;
  }
  console.log('printFragmentObj:', printFragmentObj.isLoading);
  printFragmentObj.isLoading = true;
  return new Promise(function (resolve) {
    if (beforeContentDefault && afterContentDefault) {
      return {
        beforeContent: beforeContentDefault,
        afterContent: afterContentDefault
      };
    }
    // 正文前打印的内容
    const beforeContent = [];
    // 正文后打印的内容
    let afterContent = [];

    //加入标题
    beforeContent.push(printFragmentObj.title());
    //加入发起者信息
    beforeContent.push(printFragmentObj.sender(printFrom));
    //加入附件
    {
      const fragment = printFragmentObj.attachment(printFrom);
      fragment && afterContent.push(fragment);
    }
    //加入关联文档
    {
      const fragment = printFragmentObj.document();
      fragment && afterContent.push(fragment);
    }
    let promistList = [];
    //原协同意见
    const {forwardMember} = sendCommon.useBaseInfo?.businessData?.summary||{};
    console.log(sendCommon.useBaseInfo?.businessData);
    //加入转发意见
    if (printFrom.includes('summary') && forwardMember) {

      promistList.push(
        new Promise((resolve) => {
          // 注册组件
          printFragmentObj.opinionTurn({
            callback: (fragment) => {
              if (fragment) {
                resolve(fragment);
              } else {
                resolve();
              }
            }
          });
        })
      );
    }

    if (printFrom !== 'newColl' || sendCommon.useBaseInfo.postscript) {
      //附言
      promistList.push(
        new Promise((resolve) => {
          printFragmentObj.postscript(
            {
              callback: (fragment) => {
                if (fragment) {
                  resolve(fragment);
                }else {
                  resolve();
                }
              }
            },
            printFrom
          );
        })
      );
    }

    //意见
    if (printFrom.includes('summary') && printFrom !== 'template') {
      promistList.push(
        new Promise((resolve) => {
          // 注册组件
          printFragmentObj.opinion({
            callback: (fragment) => {
              if (fragment) {
                resolve(fragment);
              }else {
                resolve(); 
              }
            }
          });
        })
      );
    }
    // 批量处理
    Promise.all(promistList).then((fragmentList) => {
      afterContent = afterContent.concat(fragmentList.filter(item=>!!item));
      printFragmentObj.isLoading = false;
      resolve({
        beforeContent,
        afterContent
      });
    });
  });
}
/**
 * 获取正文打印内容
 */
function getContentPrintFragment(printType, printFrom, callback) {
  const fnx = sendCommon.useTemplate.zwIframe.contentWindow;
  console.log(printType, printFrom);

  fnx.contentAPI.getContentPrintHTML({
    printType,
    printFrom,
    callback(data) {
      // var contentHTML, cssList, iframeURL, contentType, viewState, otherPrarams, formData;

      // iframeURL = datas.iframeURL;
      // contentHTML = datas.contentHTML;
      // cssList = datas.cssList;

      // contentType = datas.contentType;
      // viewState = datas.viewState;
      // otherPrarams = datas.otherPrarams;
      // formData = datas.formData;

      const { contentHTML, iframeURL } = data;

      // 打印回调
      let printFragment = null;
      console.log(contentHTML);

      if (contentHTML) {
        printFragment = new PrintFragment(
          globalMethods.i18n('common.toolbar.content.label'),
          contentHTML
        );
        if (
          iframeURL &&
          (printFrom == 'summary' ||
            (printFrom === 'newColl' && sendCommon.useBaseInfo.baseInfo.zwIframe.isCap4))
        ) {
          printFragment['dataContent'] = printFragment['dataHtml'];
          printFragment['dataHtml'] = iframeURL;
        }
      }

      callback(printFragment, data);
    }
  });
}

/**
 * @description: 开始打印
 * @param {Array}beforeContent 前置数据数组
 * @param {Array}afterContent 后置数据数组
 * @param {string}printType  打印的类型吧我觉得是。仅表单正文用
 * @param {string}printFrom  打印的类型吧我觉得是。表单正文和我们自己逻辑都要用
 */
export function doPrint(PrintFragmentPromise, printType, printFrom) {
  PrintFragmentPromise.then((fragmentData) => {
    let { beforeContent, afterContent } = fragmentData;
    //获取表单正文内容
    getContentPrintFragment(
      printType,
      printFrom,
      (contentFragment, { cssList, iframeURL, contentType, viewState, otherPrarams, formData }) => {
        const printDefaultSelect = []; // 默认打印的部分的索引
        const notPrintDefaultSelect = []; // 默认不勾选的部分的索引列表
        const printFragmentList = new ArrayList();

        beforeContent.forEach((d) => {
          notPrintDefaultSelect.push(printFragmentList.size());
          printFragmentList.add(d);
        });

        // 这里是正文
        let selectCommentFragment = false;
        if (contentFragment) {
          // office正文打印的时候没有正文页签
          printDefaultSelect.push(printFragmentList.size());
          printFragmentList.add(contentFragment);
        } else {
          selectCommentFragment = true;
        }

        // 当是模版的时候，这里等于0是创建人。然后在是正文，最后是附件
        if (printFrom === 'template') {
          afterContent.forEach((d) => {
            notPrintDefaultSelect.push(printFragmentList.size());
            printFragmentList.add(d);
          });
        } else {
          afterContent.forEach((d) => {
            //opinion.f.js加的（isCommentFrame）
            if (selectCommentFragment && d.isCommentFrame) {
              printDefaultSelect.push(printFragmentList.size());
            } else {
              notPrintDefaultSelect.push(printFragmentList.size());
            }
            printFragmentList.add(d);
          });
        }
        //挂载上水印，v3x写死了用window变量
        window.waterMarkBase64=getWaterMarkBase64();
        if (printFrom.includes('summary_')) {
          const print_Form = printFrom.split('_'); // 字符分割
          if (print_Form.length > 1) {
            printListLodop(
              printFragmentList,
              cssList,
              printDefaultSelect,
              notPrintDefaultSelect,
              contentType,
              viewState,
              otherPrarams,
              print_Form[1],
              formData
            );
          } else {
            printList(
              printFragmentList,
              cssList,
              printDefaultSelect,
              notPrintDefaultSelect,
              contentType,
              viewState,
              otherPrarams,
              null,
              formData
            );
          }
        } else {
          if (
            printFrom == 'summary' ||
            (printFrom === 'newColl' && sendCommon.useBaseInfo.baseInfo.zwIframe.isCap4)
          ) {
            printList(
              printFragmentList,
              cssList,
              printDefaultSelect,
              notPrintDefaultSelect,
              contentType,
              viewState,
              otherPrarams,
              iframeURL,
              formData
            );
          } else if (printFrom == 'onLineTrans') {
            // <%--在线预览打印操作--%>

            const htmlFrameIframeDom =
              sendCommon.useTemplate.zwIframe.contentWindow.document.getElementById(
                'officeTransIframe'
              );

            if (htmlFrameIframeDom != null) {
               //还得取里面一层的才行
              let htmlFrame= htmlFrameIframeDom.contentWindow.document.getElementById("htmlFrame");
              if(htmlFrame!=null){
                var htmlFrameIframeUrl = $(htmlFrame).attr('src');
                if (printFragmentList.instance[2] != null) {
                  printFragmentList.instance[2]['dataHtml'] = htmlFrameIframeUrl;
                }
                printList(
                  printFragmentList,
                  cssList,
                  printDefaultSelect,
                  notPrintDefaultSelect,
                  contentType,
                  viewState,
                  otherPrarams,
                  htmlFrameIframeUrl,
                  formData
                );
              }
            }
          } else {
            printList(
              printFragmentList,
              cssList,
              printDefaultSelect,
              notPrintDefaultSelect,
              contentType,
              viewState,
              otherPrarams,
              null,
              formData
            );
          }
        }
      }
    );
  });
}
